﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Corina.Win.MessageMonitor
{
    class Program
    {
        private static string _connStr;
        static void Main(string[] args)
        {
            _connStr = ConfigurationManager.ConnectionStrings["CORINA_SERV"].ToString();
            SqlDependency.Start(_connStr);
            UpdateGrid();

            Console.Read();
        }

        private static void UpdateGrid()
        {
            using (SqlConnection connection = new SqlConnection(_connStr))
            {
                using (SqlCommand command = new SqlCommand("SELECT [Id] ,[DataTable] ,[IdOrGuid] ,[NotifyType] ,[Read] FROM [CORINA_SERV].[dbo].[t_message_notification] WHERE [Read] = 0", connection))
                {
                    command.CommandType = CommandType.Text;
                    connection.Open();
                    SqlDependency dependency = new SqlDependency(command);
                    dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                    SqlDataReader sdr = command.ExecuteReader();
                    Console.WriteLine();
                    while (sdr.Read())
                    {
                        Console.WriteLine("Id:{0}\tUserId:{1}\tMessage:{2}", sdr["Id"].ToString(), sdr["DataTable"].ToString(), sdr["NotifyType"].ToString());
                    }
                    sdr.Close();
                }
            }
        }


        private static void dependency_OnChange(object sender, SqlNotificationEventArgs e)
        {
            UpdateGrid();
        }
    }
}
